﻿//TODO: Document everything in this file

/*
 *  Written By: Ahmad Soboh and Ahmad Assadi.
 *  All Rights Reserved - 2013.
*/

var examsTable;
var scheduleTable;
var freeDaysList;
var isLoaded = false;
var isExamsLoaded = false;

var groupsList;

var buildingArray = new Array();
function addBuilding(building) {
    for (i = 0; i < buildingArray.length; i++) {
        if (buildingArray[i] == building)
            return;
    }
    buildingArray.push(building);
}

/*
-The first time we open the free days section, the value of
this variable will be true.
*/
var isFreeDaysLoaded = false;

var isGroupsLoaded = false;


/*
-The first time we reach the end of the possible schedules we turn this variable to true
    else it's value is true.
*/
var reachedEndOfSchedules = false;

/*
- a flag which indicates if we want to jump over overlapping schedules.
*/
var noOverlapping = 0;


/*
- a flag which indicates if we want to jump over schedules with running in a 10 minutes break.
*/
var noRunning = 0;

/*
-The rank of the current schedule.
*/
var currentRank = 0;

/*
-The max number ofranks of the current choosen courses.
*/
var maxRank = 1;

/*
-This string contains the free days, and it will be sent
to the server in the url.
*/
var freeDaysLinkStr = "";

var numberOfFreeDaysLinkStr = '';

var groupsLinkStr = "";

/*
-This array will be used to show the checkboxes of the days
in the free days section.
*/
var days = new Array("Sunday", "Monday", "Tuesday",
                    "Wednesday", "Thursday", "Friday");
/*
-This array will be used to show the dropdownlist elemnts of the days
 in the free days section.
*/
var dayHours = new Array("7.00","7.30","8.00","8.30","9.00","9.30","10.00","10.30","11.00",
                         "11.30","12.00","12.30","13.00","13.30","14.00","14.30","15.00",
                          "15.30","16.00","16.30","17.00","17.30","18.00","18.30","19.00",
                          "19.30", "20.00", "20.30", "21.00");

/*
-This array will be used to save the calculated schedules, in 
order to save time and reduce communications with the server.
-Note that you must empty it when you have a change in the 
constraints.
*/
var schedules = new Array();

/*
An array of the above schedules Json's.
*/
var schedulesAsJson = new Array();



function save(userid) {

    //check if the user signed in, if not: alert('You must sign in in order to save your sechdule');

    document.cookie = 'rankNum=' + document.getElementById('rankNum').value;
    alert('cookies: ' + document.cookie);
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            //alert(j);
        }
    }
    xmlhttp.open("GET", "/User/Save/?user=" + userid, true);
    xmlhttp.send();
}

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

function Open(userid) {
    alert(document.cookie);
    deleteAllCookies();
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            //alert(j.url);
            var cookies = j.url.split(";");
            //alert(cookies[2]);
            for (var i = 0; i < cookies.length; i++) {
                document.cookie = cookies[i];
            }                   
            //alert(document.cookie);

            //now reload the page:
            location.reload(true);
        }
    }
    xmlhttp.open("GET", "/User/Open/?user=" + userid, true);
    xmlhttp.send();
}

function myInitialize(x, y) {
    var myLatlng = new google.maps.LatLng(x,y);
    var mapOptions = {
        zoom: 17,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: ''
    });
}

function getRoomMap(building) {
    var str = unescape(building).toString();
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            myInitialize(j.x, j.y);
        }
    }
    xmlhttp.open("GET", "/Scheduler/getCordinates/?name=" + building, true);
    xmlhttp.send();
}
function updateFreeDaysLinkStr() {
    freeDaysLinkStr = "";
    for (var i = 0; i < 6; i++) {
        if (document.getElementById(days[i]).checked == 1) {
            var fromList = document.getElementById(days[i] + ".from");
            freeDaysLinkStr += "&freeDays=" + fromList.options[fromList.selectedIndex].text;
            var toList = document.getElementById(days[i] + ".to");
            freeDaysLinkStr += "&freeDays=" + toList.options[toList.selectedIndex].text;
        } else {
            var fromList = document.getElementById(days[i] + ".from");
            freeDaysLinkStr += "&freeDays=" + "None";
            var toList = document.getElementById(days[i] + ".to");
            freeDaysLinkStr += "&freeDays=" + "None";
        }
    }
}

function updateNumberOfFreeDays() {
    numberOfFreeDaysLinkStr = '';
    var number = document.getElementById("numberOfFreeDays").value.toString();
    if (parseInt(number) >= 0 && parseInt(number) <= 6) {
        numberOfFreeDaysLinkStr = "&numberOfFreeDays=" + number;
    }
}

function updateGroupsLinkStr() {
    var groupsList = document.getElementById("groupsList");
    var groupsListElements = groupsList.children;
    groupsLinkStr = "";
    for (var i = 0; i < groupsList.childElementCount; i++) {
        if (groupsListElements[i].nodeName == 'INPUT' &&
            document.getElementById(groupsListElements[i].id).checked == 0) {
            groupsLinkStr += "&choosenGroups=" + groupsListElements[i].id;
        }
    }
}

function loadFreeDays() {
    var freeDaysLink = document.getElementById("freeDaysLink");
    if (isFreeDaysLoaded == true) {
        if (freeDaysLink.textContent == '<<') {
            freeDaysLink.textContent = '>>';
            document.getElementById("freeDaysLi").removeChild(freeDaysList);
        }
        else if (freeDaysLink.textContent == '>>') {
            freeDaysLink.textContent = '<<';
            document.getElementById("freeDaysLi").appendChild(freeDaysList);
        }
        return;
    }
    isFreeDaysLoaded = true;
    freeDaysLink.textContent = '<<';
    freeDaysList = document.getElementById("freeDaysList");
    freeDaysList.innerHTML = "<br>";
    for (var i = 0; i < 6; i++) {
        var newCheckBox = document.createElement('input');
        newCheckBox.type = 'checkbox';
        newCheckBox.id = days[i];
        //use the same name for all checkboxes, needed to let the action catch them:
        newCheckBox.name = "freeDays";
        newCheckBox.value = days[i];
        freeDaysList.appendChild(newCheckBox); 
        freeDaysList.innerHTML += " " + days[i] + " " + "&nbsp;";
        var fromList = document.createElement('select');
        fromList.id = days[i] + ".from";
        var hourOption = document.createElement('option');
        hourOption.innerHTML = "Any";
        fromList.appendChild(hourOption);
        for(var j = 0; j < 29; j++) {
            hourOption = document.createElement('option');
            hourOption.innerHTML = dayHours[j];
            fromList.appendChild(hourOption);
        }
        freeDaysList.innerHTML += "From:&nbsp;"
        freeDaysList.appendChild(fromList);
        var toList = document.createElement('select');
        toList.id = days[i] + "." + "to";
        hourOption = document.createElement('option');
        hourOption.innerHTML = "Any";
        toList.appendChild(hourOption);
        for (var j = 0; j < 29; j++) {
            hourOption = document.createElement('option');
            hourOption.innerHTML = dayHours[j];
            toList.appendChild(hourOption);
        }
        freeDaysList.innerHTML += "  To:  "
        freeDaysList.appendChild(toList);
        freeDaysList.innerHTML += "<br>";
    }
    freeDaysList.innerHTML += "<br>";
    var numberOfFreeDays = "<input type='number' id='numberOfFreeDays' name='quantity' style='width:30px;' min='0' max='6' >";
    var applyButton = "<input id='freeDaysApply' type='button' onclick='loadScheduleTable(3);' value='Apply' >";
    freeDaysList.innerHTML += "In case you dont't want to specify the free days you can give their number <br>";
    freeDaysList.innerHTML += "Number of free Days:&nbsp;&nbsp;";
    freeDaysList.innerHTML += numberOfFreeDays;
    freeDaysList.innerHTML += "<br>";
    freeDaysList.innerHTML += applyButton;
}


function loadGroups() {
    var groupsLink = document.getElementById("groupsLink")
    if (isGroupsLoaded == true) {
        if (groupsLink.textContent == '<<') {
            groupsLink.textContent = '>>';
            document.getElementById("groupsLi").removeChild(groupsList);
        }
        else if (groupsLink.textContent == '>>') {
            groupsLink.textContent = '<<';
            document.getElementById("groupsLi").appendChild(groupsList);
        }
        return;
    }
    isGroupsLoaded = true;
    groupsList = document.getElementById("groupsList");
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            groupsLink.textContent = '<<';
            groupsList.innerHTML = "<br>";
            var courses = new Array();
            //Build courses list
            for (var i = 0; i < j.count; i++) {
                var isInArray = false;
                for (var k = 0; k < courses.length; k++) {
                    if(j.jsonGroups[i].cname == courses[k].cname){
                        isInArray = true;
                    }
                }
                if (isInArray == false) {
                    courses.push(j.jsonGroups[i]);
                }
            }
            for (var c in courses) {
                var roles = new Array();
                //find the possible roles of this course's groups
                var groups = j.jsonGroups;
                for (g = 0; g < groups.length; g++) {
                    if (courses[c].cname == groups[g].cname) {
                        var isInArray = false; 
                        for (var i = 0; i < roles.length; i++) {
                            if (roles[i] == groups[g].r) {
                                isInArray = true;
                            }
                        }
                        if (isInArray == false) {
                            roles.push(groups[g].r);
                        }
                    }
                }
                //for each role find related group and put it in the site
                for (var r = 0; r < roles.length; r++) {
                    var p = document.createElement('p');
                    p.innerHTML += "<a href= '/Courses/Info/?number=" +
                                   courses[c].cnum +
                                   "'>" + courses[c].cname + "</a>" +
                                   "&nbsp;&nbsp;&nbsp;" +
                                   roles[r] + "<br \>";
                    groupsList.appendChild(p);
                    var groups = j.jsonGroups;
                    for (var g = 0; g < groups.length; g++) {
                        if (courses[c].cname == groups[g].cname && groups[g].r == roles[r]) {
                            var opt = groups[g].gnum;
                            var newCheckBox = document.createElement('input');
                            newCheckBox.type = 'checkbox';
                            newCheckBox.id = groups[g].gid;
                            //use the same name for all checkboxes, needed to let the action catch them:
                            newCheckBox.name = "choosenGroups";
                            newCheckBox.value = groups[g].gnum;
                            newCheckBox.defaultChecked = true;
                            groupsList.appendChild(newCheckBox);
                            groupsList.innerHTML += " " + opt + " ";
                        }
                    }
                }
            }
            groupsList.innerHTML += "<br>";
            var applyButton = "<input id='groupsApply' type='button' onclick='loadScheduleTable(4);' value='Apply' >";
            groupsList.innerHTML += applyButton;
        }
        document.getElementById("gWait").style.display = "none";
    }
    xmlhttp.open("GET", "/Courses/MyGroups/", true);
    document.getElementById("gWait").style.display = "block";
    xmlhttp.send();
}


var colors2 = new Array("yellow", "lime", "olive", "maroon", "aqua", "blue",
 	                   "fuchsia", "purple", "teal", "navy");

var colors = new Array('#f9fd01', '#FF8C00', "#198d17", " #008080", '#06f2dd', '#0618f2',
                   "#ff00ff", '#9106f2', '#7b1113', '32cd32');

var course2color = new Array();

var english2hebrew = [{ "Sunday": "א" }, { "Monday": "ב" }, { "Tuesday": "ג" },
                       { "Wednesday": "ד" }, { "Thursday": "ה" }, { "Friday": "ו" }];

var day2num = [{  "א" : 1}, { "ב" : 2}, { "ג" : 3},
                       { "ד" : 4}, { "ה" : 5}, { "ו" : 6}];


// a function reflects the no running variable. 
function noRunningClicked() {
    schedules = new Array();
    schedulesAsJson = new Array();
    if (noRunning == 0) {
        noRunning = 1;
        currentRank = 0;
        loadScheduleTable(2);
    } else {
        noRunning = 0;
    }
}

// a function reflects the no overlapping variable. 
function noOverlappingClicked() {
    schedules = new Array();
    schedulesAsJson = new Array();
    if (noOverlapping == 0) {
        noOverlapping = 1;
        currentRank = 0;
        loadScheduleTable(2);
    } else {
        noOverlapping = 0;
    }
}
//sg stands for squeezed group
function color(sg) {
    for (var i = 0; i < course2color.length; i++) {
        if (course2color[i].courseNumber == sg.courseNumber) {
            sg.color = course2color[i].color;
            return;
        }
    }
    var c2c = { courseNumber: sg.courseNumber, color: colors[i], courseName: sg.courseName };
    sg.color = colors[i];
    course2color.push(c2c);
}

//sg stands for squeezed group
function isOverlap(sg, groups) {
    for (i = 0; i < groups.length; i++) {
        if (sg.day != groups[i].day) {
            continue;
        }
        sgStart = parseFloat(sg.start);
        sgEnd = parseFloat(sg.start) + parseFloat(sg.duration);
        giStart = parseFloat(groups[i].start);
        giEnd = parseFloat(groups[i].start) + parseFloat(groups[i].duration);
        if ((
            (sgEnd <= giStart) ||
            (giEnd <= sgStart)
            ) == false) {
            return groups[i];
        }
    }
    return undefined;
}

function squeeze(groups) {
    var squeezedGroups = new Array();
    //day, start, duration, content
    while (groups.length != 0) {
        var group = groups[0];
        var x = groups.indexOf(group);
        groups.splice(x, 1);
        //sg stands for squeezed group
        var sg = {
            courseNumber: group.courseNumber,
            day: group.day,
            start: group.start,
            duration: group.duration,
            content: "<a href= '/Courses/Info/?number=" + group.courseNumber.toString().replace(' ','') +
                     "'>" + group.courseName + "</a>" + "<br>" + group.groupRole + " " + group.groupNumber + "<br>" +
                     "<a href= 'javascript: getRoomMap( \" " + escape(group.room).toString() + " \");' >  " + group.room + "</a>",
            courseName: group.courseName
        }
        addBuilding(group.room);
        var overlap = isOverlap(sg, groups);
        if (overlap == undefined) {
            color(sg);
        }
        else {
            sg.color = "red";
        }
        while (overlap != undefined) {
            groups.splice(groups.indexOf(overlap), 1);

            var max = parseFloat(sg.start) + parseFloat(sg.duration);
            var overlapEnd = parseFloat(overlap.start) + parseFloat(overlap.duration);
            if (max < overlapEnd) {
                max = overlapEnd;
            }

            if (overlap.start < sg.start) {
                sg.start = overlap.start;
                sg.content = "<a href= '/Courses/Info/?number=  " + overlap.courseNumber.toString()
                             + "'>" + overlap.courseName + "</a>"
                             + "<br>" + overlap.groupRole + " " + overlap.groupNumber
                             + "<br>"
                             + "<a href= 'javascript: getRoomMap( \" " + escape(overlap.room).toString() + " \");' >  " + overlap.room + "</a>"
                             + "<br>" + sg.content;
                addBuilding(group.room);
            }
            else {
                sg.content += "<br>" + "<a href= '/Courses/Info/?number=  " + overlap.courseNumber.toString()
                              + "'>" + overlap.courseName + "</a>" + "<br>"
                              + overlap.groupRole + " " + overlap.groupNumber
                              + "<br>"
                              + "<a href= 'javascript: getRoomMap( \" " + escape(overlap.room).toString() + " \");' >  " + overlap.room + "</a>";
                addBuilding(group.room);
            }

            sg.duration = max - parseFloat(sg.start);

            overlap = isOverlap(sg, groups);
        }

        squeezedGroups.push(sg);
    }
    return squeezedGroups;
}


function loadScheduleTable(op) {
    var table = document.getElementById("scheduleTable");
    var scheduleNum = document.getElementById("scheduleNum");
    var currentRankBox;
    var goPrev = 0;
    if (op == 1) {
        currentRank--;
        goPrev = 1;
        if (currentRank == 0) {
            currentRank = 1;
        }
    }
    if (op == 2) {
        currentRank++;
    }
    if (op == 3) {
        updateFreeDaysLinkStr();
        updateNumberOfFreeDays();
        schedules = new Array();
        schedulesAsJson = new Array();
        currentRank = 1;
    }
    if (op == 4) {
        updateGroupsLinkStr();
        schedules = new Array();
        schedulesAsJson = new Array();
        currentRank = 1;
    }
    if (op == 5)
    {
        currentRank = parseInt(document.getElementById("rankNum").value);
        if (currentRank > maxRank)
        {
            currentRank = maxRank + 1;
        }
    }
    if (schedules[currentRank] != undefined) {
        document.getElementById("rankNum").value = currentRank.toString();
        table.innerHTML = schedules[currentRank];
        document.getElementById("sWait").style.display = "none";
        return;
    }
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var schedQuery = "rank=" + currentRank + freeDaysLinkStr + numberOfFreeDaysLinkStr + groupsLinkStr
        + "&dontShowOverlappedSchedules=" + noOverlapping + "&goPrev=" + goPrev + "&noRunning=" + noRunning;
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            // getting the current rank and the max number of ranks from the Json.
            currentRank = j.rank;
            maxNumOfRank = j.max;
            if (j.count == 0) {
                    reachedEndOfSchedules = true;
                    if (currentRank > maxNumOfRank) {
                        currentRank = maxNumOfRank + 1;
                    }
                    document.getElementById("maxRank").innerHTML = maxNumOfRank;
                    document.getElementById("rankNum").value = currentRank.toString();

                    maxRank = maxNumOfRank;
                    table.innerHTML = "<b>No schedules were found !!!</b>";
                    document.getElementById("sWait").style.display = "none";
                    return;
            }
            reachedEndOfSchedules = false;
            //delete previous table
            table.innerHTML = "";
            //build header
            var header = table.insertRow(0);
            var cell = document.createElement('th');
            cell.innerHTML = "Hour/Day";
            cell.style.border = "solid";
            header.appendChild(cell);
            for (var k = 1; k < 7; k++) {
                var cell = document.createElement('th');
                cell.innerHTML = days[k - 1];
                cell.style.border = "solid";
                header.appendChild(cell);
            }

            //create all the cells and print the hours
            for (var k = 1; k < 29; k+=2) {
                var row = table.insertRow(k);
                var cell = document.createElement('td');
                x = Math.floor(k / 2) + 7;
                hour = x.toString();
                cell.innerHTML = hour + ".0";
                cell.style.border = "solid";
                row.appendChild(cell);

                for (var l = 1; l < 7; l++) {
                    var cell = document.createElement('td');
                    cell.id = (k * 7 + l + 1);
                    cell.style.border = "solid";
                    row.appendChild(cell);
                }

                var row = table.insertRow(k + 1);
                var cell = document.createElement('td');
                cell.innerHTML = hour + ".3";
                cell.style.border = "solid";
                row.appendChild(cell);

                for (var l = 1; l < 7; l++) {
                    var cell = document.createElement('td');
                    cell.id = (k + 1) * 7 + l + 1;
                    cell.style.border = "solid";
                    row.appendChild(cell);
                }
            }
            
            var coursesLink = "";
            for (var i = 0; i < j.jsTable.length; i++) {
                if (coursesLink.indexOf(j.jsTable[i].courseNumber) == -1) {
                    coursesLink += "&c=" + j.jsTable[i].courseNumber;
                }
            }

            //copy the json to the global json array and squeeze the groups
            if (!(currentRank in schedules)) {
                schedulesAsJson[currentRank] = { "jsTable": new Array(), "count": j.count, "rank": j.rank, "max": j.max }
                for (i = 0; i < j.count; i++){
                    schedulesAsJson[currentRank].jsTable[i] = 
                                {
                                    "day": j.jsTable[i].day,
                                    "start": j.jsTable[i].start,
                                    "duration": j.jsTable[i].duration,
                                    "groupNumber": j.jsTable[i].groupNumber,
                                    "courseName": j.jsTable[i].courseName,
                                    "courseNumber": j.jsTable[i].courseName,
                                    "room": j.jsTable[i].room,
                                    "groupRole": j.jsTable[i].groupRole,
                                };
                }
                // drawGoogleTimeLine();
            }
            var squeezedGroups = squeeze(j.jsTable);

            //fill in the table
            for (i = 0; i < squeezedGroups.length; i++) {
                var rowIndex = (parseInt(squeezedGroups[i].start) - 7) * 2 + 1;
                //check if it 17:00 or 17:30
                if (parseFloat(squeezedGroups[i].start) - rowIndex) {
                    rowIndex += 1;
                }
                var id = parseInt(squeezedGroups[i].day) + 1 + 1 + rowIndex * 7;
                var td = document.getElementById(id);
                td.setAttribute("align", "center");
                td.innerHTML = squeezedGroups[i].content;
                td.style.backgroundColor = squeezedGroups[i].color;
                rowspan = parseFloat(squeezedGroups[i].duration) * 2;
                td.setAttribute("rowspan", rowspan);
                for (var t = 1; t < rowspan; t++) {
                    td = document.getElementById((t * 7) + id);
                    td.parentNode.removeChild(td);
                }
            }

            if (!(currentRank in schedules)) {
                schedules[currentRank] = table.innerHTML;
            }
            document.getElementById("maxRank").innerHTML = maxNumOfRank;
            document.getElementById("rankNum").value = currentRank.toString();
            maxRank = maxNumOfRank;

            var schedLink = "/Scheduler/ScheduleViewer/?" + schedQuery;            
            schedLink += coursesLink;
            document.getElementById("largeView").setAttribute("href", schedLink);

            //fill in the google maps div:
            mapDiv = document.getElementById("mapDiv");
            if (buildingArray != null) {
                for (i = 0; i < buildingArray.length; i++) {
                    mapDiv.innerHTML = "<a href= 'javascript: getRoomMap( \" " + buildingArray[i].toString() + " \");' >  " + buildingArray[i] + "</a>" + "&nbsp" + mapDiv.innerHTML;
                }
            }
        }
        document.getElementById("sWait").style.display = "none";
        
    }
    xmlhttp.open("GET", "/Scheduler/Scheduler/?" + schedQuery, true);
    document.getElementById("sWait").style.display = "block";
    xmlhttp.send();
}


function scheduleViewer(j) {
    var table = document.getElementById("scheduleTable");
    if (j.count == 0) {
        table.innerHTML = "<b>No schedules were found !!!</b>";
        return;
    }
            //build header
            var header = table.insertRow(0);
            var cell = document.createElement('th');
            cell.innerHTML = "Hour/Day";
            cell.style.border = "solid";
            header.appendChild(cell);
            for (var k = 1; k < 7; k++) {
                var cell = document.createElement('th');
                cell.innerHTML = days[k - 1];
                cell.style.border = "solid";
                header.appendChild(cell);
            }

            //create all the cells and print the hours
            for (var k = 1; k < 29; k += 2) {
                var row = table.insertRow(k);
                var cell = document.createElement('td');
                x = Math.floor(k / 2) + 7;
                hour = x.toString();
                cell.innerHTML = hour + ".0";
                cell.style.border = "solid";
                row.appendChild(cell);

                for (var l = 1; l < 7; l++) {
                    var cell = document.createElement('td');
                    cell.id = (k * 7 + l + 1);
                    cell.style.border = "solid";
                    row.appendChild(cell);
                }

                var row = table.insertRow(k + 1);
                var cell = document.createElement('td');
                cell.innerHTML = hour + ".3";
                cell.style.border = "solid";
                row.appendChild(cell);

                for (var l = 1; l < 7; l++) {
                    var cell = document.createElement('td');
                    cell.id = (k + 1) * 7 + l + 1;
                    cell.style.border = "solid";
                    row.appendChild(cell);
                }
            }

            //squeeze the groups
            var squeezedGroups = squeeze(j.Data.jsTable);

            //fill in the table
            for (i = 0; i < squeezedGroups.length; i++) {
                var rowIndex = (parseInt(squeezedGroups[i].start) - 7) * 2 + 1;
                //check if it 17:00 or 17:30
                if (parseFloat(squeezedGroups[i].start) - rowIndex) {
                    rowIndex += 1;
                }
                var id = parseInt(squeezedGroups[i].day) + 1 + 1 + rowIndex * 7;
                var td = document.getElementById(id);
                td.setAttribute("align", "center");
                td.innerHTML = squeezedGroups[i].content;
                td.style.backgroundColor = squeezedGroups[i].color;
                rowspan = parseFloat(squeezedGroups[i].duration) * 2;
                td.setAttribute("rowspan", rowspan);
                for (var t = 1; t < rowspan; t++) {
                    td = document.getElementById((t * 7) + id);
                    td.parentNode.removeChild(td);
                }
            }
}

function loadExamsTable() {
    if (isExamsLoaded == true) {
        if (document.getElementById("examslink").textContent == '<<') {
            examsTable = document.getElementById("examsTable");
            document.getElementById("examsLi").removeChild(examsTable);
            document.getElementById("examslink").textContent = '>>';
        }
        else if (document.getElementById("examslink").textContent == '>>') {
            document.getElementById("examsLi").appendChild(examsTable);
            document.getElementById("examslink").textContent = '<<';
        }
        return;
    }
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            var table = document.getElementById("examsTable");
            //TODO: check if j is not null
            if (j.length == 0) {
                table.innerHTML = "Did you forget to choose courses?<br>";
                table.innerHTML += "Are all of your courses without exams? like projects, seminars...<br>";
                table.innerHTML += "If none of the above is the case, then please report us this bug in the "
                                    + "<a href='/Help'>Help</a> page";
                document.getElementById("eWait").style.display = "none";
                return;
            }
            isExamsLoaded = true;
            document.getElementById("examslink").textContent = '<<';

            table.style.border = "solid";
            var header = table.insertRow(0);
            var head0 = document.createElement('th');
            var head1 = document.createElement('th');
            var head2 = document.createElement('th');
            var head3 = document.createElement('th');
            header.appendChild(head0);
            header.appendChild(head1);
            header.appendChild(head2);
            header.appendChild(head3);
            head0.style.fontSize = "12pt";
            head1.style.fontSize = "12pt";
            head2.style.fontSize = "12pt";
            head3.style.fontSize = "12pt";
            head0.style.border = "solid";
            head1.style.border = "solid";
            head2.style.border = "solid";
            head3.style.border = "solid";
            head0.align = 'center';
            head1.align = 'center';
            head2.align = 'center';
            head3.align = 'center';
            head0.innerHTML = "Course&nbsp;Number";
            head1.innerHTML = "Course&nbsp;Name";
            head2.innerHTML = "Exam&nbsp;A";
            head3.innerHTML = "Exam&nbsp;B";

            for (var i = 0; i < j.length; i++) {
                var rowCount = table.rows.length;
                var row = table.insertRow(rowCount);
                var cell0 = row.insertCell(0);
                var cell1 = row.insertCell(1);
                var cell2 = row.insertCell(2);
                var cell3 = row.insertCell(3);
                cell0.style.fontSize = "12pt";
                cell1.style.fontSize = "12pt";
                cell2.style.fontSize = "12pt";
                cell3.style.fontSize = "12pt";
                cell2.style.fontWeight = 'bold';
                cell3.style.fontWeight = 'bold';
                cell0.style.border = "solid";
                cell1.style.border = "solid";
                cell2.style.border = "solid";
                cell3.style.border = "solid";
                cell0.align = 'center';
                cell1.align = 'center';
                cell2.align = 'center';
                cell3.align = 'center';
                cell0.innerHTML = j.examsJsonList[i].number;
                cell1.innerHTML = j.examsJsonList[i].name;
                cell2.innerHTML = j.examsJsonList[i].examA;
                if (j.examsJsonList[i].examAExists != "0") {
                    cell2.style.backgroundColor = "red";
                }
                cell3.innerHTML = j.examsJsonList[i].examB;
                if (j.examsJsonList[i].examBExists != "0") {
                    cell3.style.backgroundColor = "red";
                }
            }
            examsTable = document.getElementById("examsTable");
        }
        document.getElementById("eWait").style.display = "none";
    }
    xmlhttp.open("GET", "/Scheduler/Exams", true);
    document.getElementById("eWait").style.display = "block";
    xmlhttp.send();
}
